package com.openxt.nbzj.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fenjuly.library.ArrowDownloadButton;
import com.openxt.nbzj.R;
import com.openxt.nbzj.fragment.OpenxtBaseActivity;
import com.openxt.nbzj.fragment.OpenxtBaseStyle;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.FileOpenUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import qs.openxt.libs.App;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.MResource;
import qs.openxt.libs.util.SecurityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016-07-30.
 */
public class JWGWDetailsActivity extends OpenxtBaseActivity implements RemotingEx.OnActionListener, OpenxtBaseStyle.OnBackActionListener {
    private Handler mHandler = new Handler();
    private Context mContext = null;
    private RemotingModel remotingModel = null;
    private String ID = null, READSTATUSNAME = null;

    @BindView(R.id.TITLE)
    TextView TITLE;
    @BindView(R.id.DRAFTNAME)
    TextView DRAFTNAME;
    @BindView(R.id.DRAFTTIME)
    TextView DRAFTTIME;
    @BindView(R.id.CONTENT)
    TextView CONTENT;
    @BindView(R.id.FILELIST)
    LinearLayout FILELIST;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setBaseStyle(R.layout.jwgw_detail_activity, "公告详情");
        ButterKnife.bind(this);
        setActionUrl("#/jwgw");
        mContext = this;
        remotingModel = new RemotingModel(mContext);

        Bundle bundle = getIntent().getExtras();
        if(bundle == null)
            return;
        ID = bundle.getString("ID");
        READSTATUSNAME = bundle.getString("READSTATUSNAME");

        setBackAction(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initDetail();
            }
        }, 100);
    }

    private void initDetail(){
        String val = Utils.getLocalStorage(mContext, ConfigModel.PUSHNOTICE_GETPUSHNOTICE + "$" + ID);
        if(!StringUtil.isNull(val)){
            initDetailView(val);
            remotingModel.getPushnoticeGetpushnotice(this, false, ID);
        }else{
            Wait.sharedInstance().start(mContext, "正在获取详情..., 请稍候");
            remotingModel.getPushnoticeGetpushnotice(this, false, ID);
        }
        if("未读".equals(READSTATUSNAME)){
            JSONObject param = new JSONObject();
            param.put("ID", ID);
            remotingModel.getPushnoticeHasread(this, false, param);
        }
    }

    private void initDetailView(String val){
        if(StringUtil.isNull(val))
            return;
        try{
            JSONObject info = JSON.parseObject(val);
            TITLE.setText(info.getString("TITLE"));
            DRAFTNAME.setText(info.getString("DRAFTNAME"));
            DRAFTTIME.setText(info.getString("DRAFTTIME"));
            CONTENT.setText(info.getString("CONTENT"));
            JSONArray $FILELIST = info.getJSONArray("FILELIST");

            LayoutInflater inflater = LayoutInflater.from(mContext);
            FILELIST.removeAllViews();
            for(int i = 0, j = $FILELIST.size(); i < j; i++){
                JSONObject item = $FILELIST.getJSONObject(i);
                LinearLayout $item = getItem(inflater, item);
                FILELIST.addView($item);
            }
            FILELIST.invalidate();
        }catch (Exception e){

        }
    }
    private LinearLayout getItem(LayoutInflater inflater, final JSONObject item){
        String type = item.getString("TYPE");
        type = type.replace(".", "").toLowerCase();
        if("jpeg".equals(type)){
            type = "jpg";
        }
        String path = getFilePath(item);
        LinearLayout $item = (LinearLayout)inflater.inflate(R.layout.filelist_item, null);
        ImageView icon = (ImageView)$item.findViewById(R.id.icon);
        icon.setImageResource(MResource.getIdByName(mContext, "mipmap", type));
        TextView label = (TextView)$item.findViewById(R.id.label);
        label.setText(item.getString("NAME"));

        final ArrowDownloadButton arrowDownloadButton = (ArrowDownloadButton)$item.findViewById(R.id.arrow_download_button);
        if(StringUtil.isNull(path) || !new File(path).exists()) {
            arrowDownloadButton.setVisibility(View.VISIBLE);
            arrowDownloadButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downLoadEx(item, arrowDownloadButton);
                }
            });
        }else
            arrowDownloadButton.setVisibility(View.GONE);
        LinearLayout Attachment = (LinearLayout) $item.findViewById(R.id.Attachment);
        Attachment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downLoad(item, arrowDownloadButton);
            }
        });
        return $item;
    }

    private void downLoad(final JSONObject item, final ArrowDownloadButton arrowDownloadButton){
        String path = getFilePath(item);
        if(StringUtil.isNull(path) || !new File(path).exists()){
            ActivityUtil.showConfirmDialog(mContext, "文件尚未下载，是否确认下载文件？", "下载并打开", "取消", new ConfirmDialogListener() {
                @Override
                public void onOK() {
                    downLoadEx(item, arrowDownloadButton);
                }

                @Override
                public void onCancel() {

                }
            });
        }else
            openFile(path);
    }

    private void downLoadEx(final JSONObject item, final ArrowDownloadButton arrowDownloadButton){
        if (!ActivityUtil.isNetworkAvailable(mContext)) {
            Toast.makeText(mContext, mContext.getString(qs.openxt.libs.R.string.isNetworkAvailable), Toast.LENGTH_SHORT).show();
            return;
        }
        arrowDownloadButton.setVisibility(View.VISIBLE);
        arrowDownloadButton.startAnimating();
        try{
            String uri = item.getString("REAL_PATH");
            String filePath = uri.substring(uri.lastIndexOf("/") + 1);
            String download = Utils.getExternalStorageDirectory() + "/" + App.PATH_NAME + "/download/";
            File folder = new File(download);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            filePath = download + filePath;
            /*********XUtils 文件下载********/
            RequestParams params = new RequestParams(uri);
            //设置断点续传
            params.setAutoResume(true);
            params.setAutoRename(true);
            params.setSaveFilePath(filePath);
            x.http().get(params, new Callback.ProgressCallback<File>() {
                @Override
                public void onSuccess(final File result) {
                    String REAL_PATH = item.getString("REAL_PATH");
                    String u = ConfigModel.PUSHNOTICE_GETPUSHNOTICE + "$" + SecurityUtil.MD5(REAL_PATH);
                    Utils.setLocalStorage(mContext, u, result.getAbsolutePath());

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            arrowDownloadButton.setVisibility(View.GONE);
                            arrowDownloadButton.reset();
                            openFile(result.getAbsolutePath());
                        }
                    }, 320);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    arrowDownloadButton.reset();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    arrowDownloadButton.reset();
                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {

                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    arrowDownloadButton.setProgress((int) ((current / (float) total) * 100));
                }
            });
            /*********XUtils 文件下载********/
        }catch (Exception e){
            arrowDownloadButton.reset();
        }
    }

    private String getFilePath(JSONObject item){
        String REAL_PATH = item.getString("REAL_PATH");
        String u = ConfigModel.PUSHNOTICE_GETPUSHNOTICE + "$" + SecurityUtil.MD5(REAL_PATH);
        String path = Utils.getLocalStorage(mContext, u);
        return path;
    }

    private void openFile(String file){
        FileOpenUtil.openFile(this, new File(file));
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        Wait.sharedInstance().stop();
        if(actionName.equals(ConfigModel.PUSHNOTICE_GETPUSHNOTICE + "$" + ID)){
            Utils.setLocalStorage(mContext, ConfigModel.PUSHNOTICE_GETPUSHNOTICE + "$" + ID, reVal);
            initDetailView(reVal);
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        Wait.sharedInstance().stop();
        showMsg(errorVal);
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    @Override
    public void onBackAction() {
        setResult(RESULT_OK);
        finish();
    }
}
